package com.chuanyekeji.aokai.Controller;

import com.chuanyekeji.aokai.AokaiApplication;
import com.chuanyekeji.aokai.Config.ReadPathConfig;
import com.chuanyekeji.aokai.Entity.Cases;
import com.chuanyekeji.aokai.Entity.Information;
import com.chuanyekeji.aokai.Entity.Model.CaseJsonModel;
import com.chuanyekeji.aokai.Entity.Model.InformationModel;
import com.chuanyekeji.aokai.Entity.Seo;
import com.chuanyekeji.aokai.Mapper.InformationMapper;
import com.chuanyekeji.aokai.Mapper.SeoMapper;
import com.chuanyekeji.aokai.Util.DateUtil;
import com.chuanyekeji.aokai.Util.FileUtil;
import com.chuanyekeji.aokai.Util.ReturnData;
import com.google.gson.Gson;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.format.annotation.DateTimeFormat;
import org.springframework.util.ResourceUtils;
import org.springframework.web.bind.annotation.CrossOrigin;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.util.*;
@CrossOrigin(origins = "*",maxAge = 3600)
@RestController
public class InformationController {

    @Autowired
    InformationMapper informationMapper;

    @Autowired
    ReadPathConfig readPathConfig;

    @Autowired
    SeoMapper seoMapper;

    /**
     * 保存新资讯
     * @param content
     * @param code
     * @param title
     * @return
     */
    @RequestMapping("addInformation")
    String addInformation(String content,String code,String title,String describe,String titles,String descs,String keyword,
                          String title_en,String describe_en) {
        Seo seo = new Seo();
        seo.setTitle(titles);
        seo.setDescs(descs);
        seo.setKeyword(keyword);
        seo.setIsFirstPage(0);
        seoMapper.insertSelective(seo);
        //获取根目录
        String firstImagePath = "";
        try {
            firstImagePath = ResourceUtils.getURL("classpath:").getPath();
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        }
        //获取文件上传时的项目相对路径
        File file = new File(firstImagePath,"static/" + readPathConfig.getInformation());
        if(!file.exists()) {
            file.mkdirs();
        }
        Information information = new Information();
        information.setCreateTime(DateUtil.dateTimeToString(new Date()));
        information.setInformationTitle(title);
        information.setInformationTitle_en(title_en);
        information.setInformationDescribe(describe);
        information.setInformationDescribe_en(describe_en);
        information.setInformationImage(code);
        information.setInformationUrl(content);
        information.setIsShow(1);
        information.setSeo(seo);
        informationMapper.insertSelective(information);
        return "发布成功";
    }

    /**
     * 保存资讯图片
     * @param image
     * @return
     */
    @RequestMapping("upImageOfInformation")
    String upImageOfInformation(@RequestParam(value = "image",required = false) MultipartFile image) {
        //封装返回数据
        Map<String,Object> data = new HashMap<>();
        Gson gson = new Gson();
        //获取根目录
        String firstImagePath = "";
        try {
            firstImagePath = ResourceUtils.getURL("classpath:").getPath();
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        }
        //获取文件上传时的项目相对路径
        File file = new File(firstImagePath,"static/" + readPathConfig.getInformation());
        firstImagePath = file.getAbsolutePath() + "/";
        String fileName = image.getOriginalFilename();
        //随机码
        String imgCode = UUID.randomUUID().toString();

        //获取点最后出现的位置
        int lastIndex = fileName.lastIndexOf(".");
        //字符串最后的位置
        int endIndex = fileName.length();
        // 获取文件后缀名
        String str = fileName.substring(lastIndex,endIndex);
        String imageName = imgCode + str;
        try {
            //保存图片
            if(FileUtil.uploadFile(image.getBytes(), firstImagePath,imageName)) {
                data.put("code",0);
                data.put("url",readPathConfig.getInformation() + "/" + imageName);
            } else {
                data.put("code",1);
                data.put("message","error");
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return gson.toJson(data);
    }

    /**
     * 获取资讯信息
     * @param id
     * @return
     */
    @RequestMapping("getInformation")
    String getInformation(int id,HttpSession session) {
        Information information = informationMapper.selectByPrimaryKey(id);
        Information nextInformation = informationMapper.selectNextId(id);
        Information lastInformation = informationMapper.selectLastId(id);
        int nextId = -1;
        int lastId = -1;
        String nextName = "";
        String lastName = "";
        if(nextInformation != null) {
            nextId = nextInformation.getId();
            nextName = nextInformation.getInformationTitle();
        }
        if(lastInformation != null) {
            lastId = lastInformation.getId();
            lastName = lastInformation.getInformationTitle();
        }
        if(AokaiApplication.language.get(session.getId()).equals("en")) {
            information.setInformationDescribe(information.getInformationDescribe_en());
            information.setInformationTitle(information.getInformationTitle_en());
        }
        Map<String,Object> data = new HashMap<>();
        data.put("data",information);
        data.put("nextPage",nextId);
        data.put("nextName",nextName);
        data.put("lastPage",lastId);
        data.put("lastName",lastName);
        return ReturnData.success("success",new Gson().toJson(data));
    }

    /**
     * 按分页获取数据
     * @param rows
     * @param page
     * @return
     */
    @RequestMapping("getInformationList")
    String getInformationList(@RequestParam(required=false,defaultValue="1") int page, @RequestParam(required=false,defaultValue="10") int rows) {
        int lastRow = rows * page;
        int indexRow = lastRow - rows;
        List<Information> informationList = informationMapper.getInformationList(indexRow,lastRow);
        List<Information> informations = new ArrayList<>();
        for(Information i : informationList) {
            i.setCreateTime(DateUtil.dateDayToString(DateUtil.stringToDate(i.getCreateTime())));
            informations.add(i);
        }
        Map<String,Object> data = new HashMap<>();
        data.put("total",informationMapper.getInformationCount());
        data.put("rows",informations);
        return ReturnData.success("success",new Gson().toJson(data));
    }

    /**
     * 按分页获取数据
     * @param rows
     * @param page
     * @return
     */
    @RequestMapping("getInformationListByJson")
    String getInformationListByJson(@RequestParam(required=false,defaultValue="1") int page, @RequestParam(required=false,defaultValue="10") int rows,
                                    HttpSession session
    ) {
        int lastRow = rows * page;
        int indexRow = lastRow - rows;
        List<Information> informationList = informationMapper.getInformationList(indexRow,lastRow);
        List<InformationModel> informationModelList = new ArrayList<>();
        for(Information i : informationList) {
            InformationModel model = new InformationModel();
            model.setId(i.getId());
            model.setSeoTitle(i.getSeo().getTitle());
            model.setSeoKeyword(i.getSeo().getKeyword());
            model.setSeoDescs(i.getSeo().getDescs());
            model.setInformationTitle_en(i.getInformationTitle_en());
            model.setInformationTitle(i.getInformationTitle());
            model.setInformationImage(i.getInformationImage());
            model.setInformationDescribe_en(i.getInformationDescribe_en());
            model.setInformationDescribe(i.getInformationDescribe());
            informationModelList.add(model);
        }

        System.out.println(new Gson().toJson(informationModelList));
        return new Gson().toJson(informationModelList);
    }

    /**
     * 删除资讯
     * @param id
     * @return
     */
    @RequestMapping("delInformation")
    String delInformation(int id) {
        informationMapper.deleteByPrimaryKey(id);
        return ReturnData.success("删除成功");
    }

    /**
     * 修改资讯描述
     * @param id
     * @param body
     * @return
     */
    @RequestMapping("changeInformationBody")
    String changeInformationBody(int id,String body) {
        Information information = informationMapper.selectByPrimaryKey(id);
        information.setInformationUrl(body);
        informationMapper.updateByPrimaryKeySelective(information);
        return ReturnData.success("修改成功");
    }

    /**
     * 修改资讯
     * @return
     */
    @RequestMapping("changeInformation")
    String changeInformation(Information information,String seoTitle,String seoKeyword,String seoDescs) {
        Information info = informationMapper.selectByPrimaryKey(information.getId());
        info.setInformationDescribe(information.getInformationDescribe());
        info.setInformationImage(information.getInformationImage());
        info.setInformationTitle(information.getInformationTitle());
        info.setInformationDescribe_en(information.getInformationDescribe_en());
        info.setInformationTitle_en(information.getInformationTitle_en());
        Seo seo = new Seo();
        seo.setId(info.getSeo().getId());
        seo.setDescs(seoDescs);
        seo.setKeyword(seoKeyword);
        seo.setTitle(seoTitle);
        seoMapper.updateByPrimaryKeySelective(seo);
        informationMapper.updateByPrimaryKeySelective(info);
        return ReturnData.success("修改成功");
    }
}
